<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃
 * Date: 2015-09-09
 */
namespace app\admin\controller;
use app\admin\logic\OrderLogic;
use think\AjaxPage;
use think\Page;
use think\Db;

class Order extends Base {
    public  $order_status;
    public  $pay_status;
    public  $shipping_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        // 订单 支付 发货状态
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }

    /*
     *订单首页
     */
    public function index(){
    	$begin = date('Y-m-d',strtotime("-1 year"));//30天前
    	$end = date('Y/m/d',strtotime('+1 days')); 	
    	$this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
    }

    /*
     *Ajax首页
     */
    public function ajaxindex(){
        $orderLogic = new OrderLogic();       
        $timegap = I('timegap');
        if($timegap){
        	$gap = explode('-', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }else{
            //@new 新后台UI参数
            $begin = strtotime(I('add_time_begin'));
            $end = strtotime(I('add_time_end'));
        }
        
        // 搜索条件
        $condition = array();
        $keyType = I("keytype");
        $keywords = I('keywords','','trim');
        
        $consignee =  ($keyType && $keyType == 'consignee') ? $keywords : I('consignee','','trim');
        $consignee ? $condition['consignee'] = trim($consignee) : false;
        
        
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        }
        
        $order_sn = ($keyType && $keyType == 'order_sn') ? $keywords : I('order_sn') ;
        $order_sn ? $condition['order_sn'] = trim($order_sn) : false;
        
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('order')->where($condition)->count();
        $Page  = new AjaxPage($count,20);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if($key == 'add_time'){
                $between_time = explode(',',$val[1]);
                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
                $Page->parameter['timegap'] = $parameter_add_time;
            }else{
                $Page->parameter[$key]   =  urlencode($val);
            }
        }
        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }

    
    /*
     * ajax 发货订单列表
    */
    public function ajaxdelivery(){
    	$orderLogic = new OrderLogic();
    	$condition = array();
    	I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
    	I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
    	$shipping_status = I('shipping_status');
    	$condition['shipping_status'] = empty($shipping_status) ? array('neq',1) : $shipping_status;
        $condition['order_status'] = array('in','1,2,4');
    	$count = M('order')->where($condition)->count();
    	$Page  = new AjaxPage($count,10);
    	//搜索条件下 分页赋值
    	foreach($condition as $key=>$val) {
            if(!is_array($val)){
                $Page->parameter[$key]   =   urlencode($val);
            }
    	}
    	$show = $Page->show();
    	$orderList = M('order')->where($condition)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
    	$this->assign('orderList',$orderList);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->assign('pager',$Page);
    	return $this->fetch();
    }
    
    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        
        $cellar_spec = C('cellar_spec');
        foreach($orderGoods as $key=>$val){
        	//$type = M("goods")->where("goods_id",$val['goods_id'])->getField('type');
        	$type = $orderGoods[$key]['type'];
        	if($type == 1){
	        	if(!empty($val['other_content'])){
		            $other_content = json_decode($val['other_content'],true);
		            foreach($other_content as $k=>$v){
		            	$spec[$key]['capacity'] = $other_content['capacity'];
		            	$spec[$key]['buy_type'] = $other_content['buy_type'];
	            		if($k=='buy_type' && $v==2){
	            			$spec[$key]['cellar_years'] = $other_content['cellar_years'];
	            			$spec[$key]['cellar_type'] = $other_content['cellar_type'];	
	            		}
	            		if($k=='cellar_type' && $v==1 && $spec[$key]['buy_type']==2){
	            			$spec[$key]['yy_time'] = $other_content['yy_time'];
		            	    $spec[$key]['yy_num'] = $other_content['yy_num'];
	            		}
	
		            }
		            
		            
		            //拼接成字符串在前台直接输出
		            $orderGoods[$key]['spec_key_name'] = '';
		            $i=0;
		            foreach($spec[$key] as $k=>$v){
		            	$i++;
		         	  	if(is_array($cellar_spec[$k])){
		         	  		$orderGoods[$key]['spec_key_name'] .= "{$cellar_spec[$k][0]}:{$cellar_spec[$k][$v]}&nbsp;&nbsp;";	
		         	  	}else{	
		         	  	    $orderGoods[$key]['spec_key_name'] .= "{$cellar_spec[$k]}:{$v}&nbsp;&nbsp;";	
		         	  	}
		         	  	if($i%2==0){
		         	  		$orderGoods[$key]['spec_key_name'] .= "<br>";
		         	  	}
		         	}
		
		            //以数组方式输出，在前台拼接
		            //$result['cartList'][$key]['spec_key_name'] = $spec[$key];
	          }
	        }    
 			//序列化other_content
	        $orderGoods[$key]['other_content'] = json_decode($val['other_content'],"true");
	        $other_content = $orderGoods[$key]['other_content'];
	        $other_content['despic'] = empty($orderGoods[$key]['other_content']['despic'])?"/public/upload/destine/0_1489368120.png":$orderGoods[$key]['other_content']['despic'];
	        $other_content['message'] = empty($orderGoods[$key]['other_content']['message'])?"":$orderGoods[$key]['other_content']['message'];
	        $other_content['destine_status'] = empty($orderGoods[$key]['other_content']['destine_status'])?0:$orderGoods[$key]['other_content']['destine_status'];
	        $date['other_content'] = json_encode($other_content);
	        M('order_goods')->where("rec_id",$orderGoods[$key]['rec_id'])->save($date);
	        $orderGoods[$key]['other_content'] = $other_content;
	        $orderGoods[$key]['other_content']['despic1'] = basename($other_content['despic']);
	        if(!empty($orderGoods[$key]['other_content']['workspic'])){
	            $orderGoods[$key]['other_content']['workLast'] = end($orderGoods[$key]['other_content']['workspic']);        
	        }
        }
        $button = $orderLogic->getOrderButton($order);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
        $userIds = array();
        //查找用户昵称
        foreach ($action_log as $k => $v){
            $userIds[$k] = $v['action_user'];
        }
        if($userIds && count($userIds) > 0){
            $users = M("users")->where("user_id in (".implode(",",$userIds).")")->getField("user_id , nickname" , true);
        }
        $this->assign('users',$users);
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
        	if($val['goods_num']>1){
        		$split = 1;
        	}
        }
        $this->assign('split',$split);
        $this->assign('button',$button);
        return $this->fetch();
    }

    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function edit_order(){
    	$order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        } 
    
        $orderGoods = $orderLogic->getOrderGoods($order_id);
                
       	if(IS_POST)
        {
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注
            $order['admin_note'] = I('admin_note'); //                  
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');            
            $order['pay_code'] = I('payment');// 支付方式            
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');                            
            $goods_id_arr = I("goods_id/a");
            $new_goods = $old_goods_arr = array();
            //################################订单添加商品
            if($goods_id_arr){
            	$new_goods = $orderLogic->get_spec_goods($goods_id_arr);
            	foreach($new_goods as $key => $val)
            	{
            		$val['order_id'] = $order_id;
            		$rec_id = M('order_goods')->add($val);//订单添加商品
            		if(!$rec_id)
            			$this->error('添加失败');
            	}
            }
            
            //################################订单修改删除商品
            $old_goods = I('old_goods/a');
            foreach ($orderGoods as $val){
            	if(empty($old_goods[$val['rec_id']])){
            		M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
            	}else{
            		//修改商品数量
            		if($old_goods[$val['rec_id']] != $val['goods_num']){
            			$val['goods_num'] = $old_goods[$val['rec_id']];
            			M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
            		}
            		$old_goods_arr[] = $val;
            	}
            }
            
            $goodsArr = array_merge($old_goods_arr,$new_goods);
            $result = calculate_price($order['user_id'],$goodsArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
            if($result['status'] < 0)
            {
            	$this->error($result['msg']);
            }
       
            //################################修改订单费用
            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price'];//物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价           
            $o = M('order')->where('order_id='.$order_id)->save($order);
            
            $l = $orderLogic->orderActionLog($order_id,'edit','修改订单');//操作日志
            if($o && $l){
            	$this->success('修改成功',U('Admin/Order/editprice',array('order_id'=>$order_id)));
            }else{
            	$this->success('修改失败',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        // 获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        
        $this->assign('order',$order);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        return $this->fetch();
    }
    
    /*
     * 拆分订单
     */
    public function split_order(){
    	$order_id = I('order_id');
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	if($order['shipping_status'] != 0){
    		$this->error('已发货订单不允许编辑');
    		exit;
    	}
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
    	if(IS_POST){
    		$data = I('post.');
    		//################################先处理原单剩余商品和原订单信息
    		$old_goods = I('old_goods/a');
    		
    		foreach ($orderGoods as $val){
    			if(empty($old_goods[$val['rec_id']])){
    				M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
    			}else{
    				//修改商品数量
    				if($old_goods[$val['rec_id']] != $val['goods_num']){
    					$val['goods_num'] = $old_goods[$val['rec_id']];
    					M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
    				}
    				$oldArr[] = $val;//剩余商品
    			}
    			$all_goods[$val['rec_id']] = $val;//所有商品信息
    		}
    		$result = calculate_price($order['user_id'],$oldArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
    		if($result['status'] < 0)
    		{
    			$this->error($result['msg']);
    		}
    		//修改订单费用
    		$res['goods_price']    = $result['result']['goods_price']; // 商品总价
    		$res['order_amount']   = $result['result']['order_amount']; // 应付金额
    		$res['total_amount']   = $result['result']['total_amount']; // 订单总价
    		M('order')->where("order_id=".$order_id)->save($res);
			//################################原单处理结束
			
    		//################################新单处理
    		for($i=1;$i<20;$i++){
                $temp = $this->request->param($i.'_old_goods/a');
    			if(!empty($temp)){
    				$split_goods[] = $temp;
    			}
    		}

    		foreach ($split_goods as $key=>$vrr){
    			foreach ($vrr as $k=>$v){
    				$all_goods[$k]['goods_num'] = $v;
    				$brr[$key][] = $all_goods[$k];
    			}
    		}

    		foreach($brr as $goods){
    			$result = calculate_price($order['user_id'],$goods,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],0,0,0,0);
    			if($result['status'] < 0)
    			{
    				$this->error($result['msg']);
    			}
    			$new_order = $order;
    			$new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
    			$new_order['parent_sn'] = $order['order_sn'];
    			//修改订单费用
    			$new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
    			$new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
    			$new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
    			$new_order['add_time'] = time();
    			unset($new_order['order_id']);
    			$new_order_id = DB::name('order')->insertGetId($new_order);//插入订单表
    			foreach ($goods as $vv){
    				$vv['order_id'] = $new_order_id;
    				unset($vv['rec_id']);
    				$nid = M('order_goods')->add($vv);//插入订单商品表
    			}
    		}
    		//################################新单处理结束
    		$this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            exit;
    	}
    	
    	foreach ($orderGoods as $val){
    		$brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
    	}
    	$this->assign('order',$order);
    	$this->assign('goods_num_arr',json_encode($brr));
    	$this->assign('orderGoods',$orderGoods);
    	return $this->fetch();
    }
    
    /*
     * 价钱修改
     */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $this->editable($order);
        if(IS_POST){
        	$admin_id = session('admin_id');
            if(empty($admin_id)){
                $this->error('非法操作');
                exit;
            }
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
			$update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'];
            $row = M('order')->where(array('order_id'=>$order_id))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Admin/Order/editprice',array('order_id'=>$order_id)));
            }else{
                $this->success('操作成功',U('Admin/Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        return $this->fetch();
    }

    /**
     * 订单删除
     * @param int $id 订单id
     */
    public function delete_order($order_id){
    	$order_id = (int)$order_id;
    	$orderLogic = new OrderLogic();
    	$del = $orderLogic->delOrder($order_id);
        if($del){
            $this->success('删除订单成功');
        }else{
        	$this->error('订单删除失败');
        }
    }
    
    /**
     * 订单取消付款
     */
    public function pay_cancel($order_id){
    	if(I('remark')){
    		$data = I('post.');
    		$note = array('退款到用户余额','已通过其他方式退款','不处理，误操作项');
    		if($data['refundType'] == 0 && $data['amount']>0){
    			accountLog2($data['user_id'],$data['order_id'], $data['amount'], 0,  '退款到用户余额');
    		}
    		if($data['refundType'] == 1 && $data['amount']>0){//微信退款
    		    //查询退款信息
    		    $order_info = M('order')->where("order_id=$order_id")->find();
		        $pay_info = M("pay_log")->where("order_sn",$order_info['order_sn'])->find();
		        if($pay_info){//有支付信息
		            //查询退款申请
		            $refund_info =M('refund_log')->where('pay_id',$pay_info['pay_id'])->find();
		            if(empty($refund_info)){//无退款记录,记录一个
		                $refund_log = array(
		                    'pay_id' => $pay_info['pay_id'],
		                    'out_trade_no' => $pay_info['out_trade_no'],
		                    'out_refund_no' => "TKWX".getOrdersn(),
		                    'user_id' => $pay_info['user_id'],
		                    'refund_fee' => $pay_info['total_fee'],
		                    'op_user_id' => '1400627102',
		                    'addtime' =>time(),
		                    'status' => 0,
		                    'return_type' => 1,//原途径退款
		                );
		                $refund_info['refund_id'] = M('refund_log')->add($refund_log);
		            }
		            order_WX_refund($refund_info['refund_id']);//微信退款
		        }else{
		            exit("<script>alert('无交易记录，退款失败');</script>");
		        }
    		}
    		$orderLogic = new OrderLogic();
            $orderLogic->orderProcessHandle($data['order_id'],'pay_cancel');
    		$d = $orderLogic->orderActionLog($data['order_id'],'pay_cancel',$data['remark'].':'.$note[$data['refundType']]);
    		if($d){
    			exit("<script>window.parent.pay_callback(1);</script>");
    		}else{
    			exit("<script>window.parent.pay_callback(0);</script>");
    		}
    	}else{
    		$order = M('order')->where("order_id=$order_id")->find();
    		$this->assign('order',$order);
    		return $this->fetch();
    	}
    }

    /**
     * 订单打印
     * @param int $id 订单id
     */
    public function order_print(){
    	$order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        $order['full_address'] = $order['province'].' '.$order['city'].' '.$order['district'].' '. $order['address'];
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $shop = tpCache('shop_info');
        $this->assign('order',$order);
        $this->assign('shop',$shop);
        $this->assign('orderGoods',$orderGoods);
        $template = I('template','print');
        return $this->fetch($template);
    }

    /**
     * 快递单打印
     */
    public function shipping_print(){
        $order_id = I('get.order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //查询是否存在订单及物流
        $shipping = M('plugin')->where(array('code'=>$order['shipping_code'],'type'=>'shipping'))->find();        
        if(!$shipping){
        	$this->error('物流插件不存在');
        }
		if(empty($shipping['config_value'])){
			$this->error('请设置'.$shipping['name'].'打印模板');
		}
        $shop = tpCache('shop_info');//获取网站信息
        $shop['province'] = empty($shop['province']) ? '' : getRegionName($shop['province']);
        $shop['city'] = empty($shop['city']) ? '' : getRegionName($shop['city']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        if(empty($shipping['config'])){
        	$config = array('width'=>840,'height'=>480,'offset_x'=>0,'offset_y'=>0);
        	$this->assign('config',$config);
        }else{
        	$this->assign('config',unserialize($shipping['config']));
        }
        $template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
        		 "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话", 
        		"收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月", 
        		"时间-日","时间-当前日期","订单-订单号", "订单-备注","订单-配送费用");
        $content_var = array($shop['store_name'],$shop['contact'],$shop['phone'],$shop['province'],$shop['city'],
        	$shop['district'],$shop['phone'],$shop['address'],$order['consignee'],$order['mobile'],$order['phone'],
        	$order['province'],$order['city'],$order['district'],$order['zipcode'],$order['address'],date('Y'),date('M'),
        	date('d'),date('Y-m-d'),$order['order_sn'],$order['admin_note'],$order['shipping_price'],
        );
        $shipping['config_value'] = str_replace($template_var,$content_var, $shipping['config_value']);
        $this->assign('shipping',$shipping);
        return $this->fetch("Plugin/print_express");
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new OrderLogic();
		$data = I('post.');
		$res = $orderLogic->deliveryHandle($data);
		if($res){
			$this->success('操作成功',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
		}else{
			$this->success('操作失败',U('Admin/Order/delivery_info',array('order_id'=>$data['order_id'])));
		}
    }

    
    public function delivery_info(){
    	$order_id = I('order_id');
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
		$delivery_record = M('delivery_doc')->alias('d')->join('__ADMIN__ a','a.admin_id = d.admin_id')->where('d.order_id='.$order_id)->select();
		if($delivery_record){
			$order['invoice_no'] = $delivery_record[count($delivery_record)-1]['invoice_no'];
		}
		//快递
		$shipping_list = M('plugin')->where(array("type"=>'shipping',"status"=>"1"))->select();
		$this->assign('shipping_list',$shipping_list);
		$this->assign('order',$order);
		$this->assign('orderGoods',$orderGoods);
		$this->assign('delivery_record',$delivery_record);//发货记录
    	return $this->fetch();
    }
    
    /**
     * 发货单列表
     */
    public function delivery_list(){
        return $this->fetch();
    }
	
    /*
     * ajax 退货订单列表
     */
    public function ajax_return_list(){
        // 搜索条件        
        $order_sn =  trim(I('order_sn'));
        $order_by = I('order_by') ? I('order_by') : 'id';
        $sort_order = I('sort_order') ? I('sort_order') : 'desc';
        $status =  I('status');
        
        $where = " 1 = 1 ";
        $order_sn && $where.= " and order_sn like '%$order_sn%' ";
        empty($order_sn) && $where.= " and status = '$status' ";
        $count = M('return_goods')->where($where)->count();
        $Page  = new AjaxPage($count,13);
        $show = $Page->show();
        $list = M('return_goods')->where($where)->order("$order_by $sort_order")->limit("{$Page->firstRow},{$Page->listRows}")->select();        
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr)){
            $goods_list = M('goods')->where("goods_id in (".implode(',', $goods_id_arr).")")->getField('goods_id,goods_name');
        }
        $this->assign('goods_list',$goods_list);
        $this->assign('list',$list);
        $this->assign('pager',$Page);
        $this->assign('page',$show);// 赋值分页输出
        return $this->fetch();
    }
    
    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id = I('get.id');
        M('return_goods')->where("id = $id")->delete(); 
        $this->success('成功删除!');
    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $id = I('id');
        $return_goods = M('return_goods')->where("id= $id")->find();
        if($return_goods['imgs'])            
             $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        //查询支付信息
        $pay_info = M("pay_log")->where("order_sn",$return_goods['order_sn'])->find();
        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $type_msg = array('退换','换货');
        $status_msg = array('未处理','处理中','已完成');
        if(IS_POST)
        {
            $data['type'] = I('type');
            $data['status'] = I('status');
            $data['remark'] = I('remark');                                    
            $note ="退换货:{$type_msg[$data['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $id")->save($data);    
            if($result)
            {        
            	$type = empty($data['type']) ? 2 : 3;
            	$where = " order_id = ".$return_goods['order_id']." and goods_id=".$return_goods['goods_id'];
            	M('order_goods')->where($where)->save(array('is_send'=>$type));//更改商品状态        
                $orderLogic = new OrderLogic();
                $log = $orderLogic->orderActionLog($return_goods[order_id],'refund',$note);
                $this->success('修改成功!');            
                exit;
            }  
        }        
        
        $this->assign('id',$id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品
        $this->assign("pay_info",$pay_info);
        $this->assign('return_goods',$return_goods)
        ;// 退换货               
        return $this->fetch();
    }
    
    /**
     * 管理员生成申请退货单
     */
    public function add_return_goods()
   {                
            $order_id = I('order_id'); 
            $goods_id = I('goods_id');
                
            $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id")->find();            
            if(!empty($return_goods))
            {
                $this->error('已经提交过退货申请!',U('Admin/Order/return_list'));
                exit;
            }
            $order = M('order')->where("order_id = $order_id")->find();
            
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order['order_sn']; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $order[user_id];            
            $data['remark'] = '管理员申请退换货'; // 问题描述            
            M('return_goods')->add($data);            
            $this->success('申请成功,现在去处理退货',U('Admin/Order/return_list'));
            exit;
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){    	
        $orderLogic = new OrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');

        $alldata = I('post.');//收集数据
        $cellar = $alldata['cellar'];
        //$cellar = $alldata['cellar']);//如果是藏酒订单，确认订单时，必须传入藏酒酒坛编号
        
        if($action && $order_id){
            if($action !=='pay'){
                $res = $orderLogic->orderActionLog($order_id,$action,I('note'));
            }
        	 $a = $orderLogic->orderProcessHandle($order_id,$action,array('note'=>I('note'),'admin_id'=>0),$cellar);
        	 if($res !== false && $a !== false){
                 if ($action == 'remove') {
                     exit(json_encode(array('status' => 1, 'msg' => '操作成功', 'data' => array('url' => U('admin/order/index')))));
                 }
        	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
        	 }else{
                 if ($action == 'remove') {
                     exit(json_encode(array('status' => 0, 'msg' => '操作失败', 'data' => array('url' => U('admin/order/index')))));
                 }
        	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
        	 }
        }else{
        	$this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
        }
    }
    
    public function order_log(){
    	$timegap = I('timegap');
    	if($timegap){
    		$gap = explode('-', $timegap);
    		$begin = strtotime($gap[0]);
    		$end = strtotime($gap[1]);
    	}else{
    	    //@new 兼容新模板
    	    $begin = strtotime(I('timegap_begin'));
    	    $end = strtotime(I('timegap_end'));
    	}
    	$condition = array();
    	$log =  M('order_action');
    	if($begin && $end){
    		$condition['log_time'] = array('between',"$begin,$end");
    	}
    	$admin_id = I('admin_id');
		if($admin_id >0 ){
			$condition['action_user'] = $admin_id;
		}
    	$count = $log->where($condition)->count();
    	$Page = new Page($count,20);
    	foreach($condition as $key=>$val) {
    		$Page->parameter[$key] = urlencode($val);
    	}
    	$show = $Page->show();
    	$list = $log->where($condition)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('list',$list);
    	$this->assign('pager',$Page);
    	$this->assign('page',$show);   	
    	$admin = M('admin')->getField('admin_id,user_name');
    	$this->assign('admin',$admin);    	
    	return $this->fetch();
    }

    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }

    public function export_order()
    {
    	//搜索条件
		$where = 'where 1=1 ';
		$consignee = I('consignee');
		if($consignee){
			$where .= " AND consignee like '%$consignee%' ";
		}
		$order_sn =  I('order_sn');
		if($order_sn){
			$where .= " AND order_sn = '$order_sn' ";
		}
		if(I('order_status')){
			$where .= " AND order_status = ".I('order_status');
		}
		
		$timegap = I('timegap');
		if($timegap){
			$gap = explode('-', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
			$where .= " AND add_time>$begin and add_time<$end ";
		}
		    
		$sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
    	$orderList = DB::query($sql);
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
    	$strTable .= '</tr>';
	    if(is_array($orderList)){
	    	$region	= M('region')->getField('id,name');
	    	foreach($orderList as $k=>$val){
	    		$strTable .= '<tr>';
	    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].' </td>';	    		
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
                        $strTable .= '<td style="text-align:left;font-size:12px;">'."{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['address']}".' </td>';                        
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$this->shipping_status[$val['shipping_status']].'</td>';
	    		$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
	    		$strGoods="";
	    		foreach($orderGoods as $goods){
	    			$strGoods .= "商品编号：".$goods['goods_sn']." 商品名称：".$goods['goods_name'];
	    			if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
	    			$strGoods .= "<br />";
	    		}
	    		unset($orderGoods);
	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
	    		$strTable .= '</tr>';
	    	}
	    }
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
    }
    
    /**
     * 退货单列表
     */
    public function return_list(){
        return $this->fetch();
    }
    
    /**
     * 添加一笔订单
     */
    public function add_order()
    {
        $order = array();
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //  获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        if(IS_POST)
        {
            $order['user_id'] = I('user_id');// 用户id 可以为空
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            $order['admin_note'] = I('admin_note'); // 管理员备注            
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
            $order['admin_note'] = I('admin_note'); // 
            $order['add_time'] = time(); //                    
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');            
            $order['pay_code'] = I('payment');// 支付方式            
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');            
                            
            $goods_id_arr = I("goods_id/a");
            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);          
            $result = calculate_price($order['user_id'],$order_goods,$order['shipping_code'],0,$order[province],$order[city],$order[district],0,0,0,0);      
            if($result['status'] < 0)	
            {
                 $this->error($result['msg']);      
            } 
           
           $order['goods_price']    = $result['result']['goods_price']; // 商品总价
           $order['shipping_price'] = $result['result']['shipping_price']; //物流费
           $order['order_amount']   = $result['result']['order_amount']; // 应付金额
           $order['total_amount']   = $result['result']['total_amount']; // 订单总价
           
            // 添加订单
            $order_id = M('order')->add($order);
            $order_insert_id = DB::getLastInsID();
            if($order_id)
            {
                foreach($order_goods as $key => $val)
                {
                    $val['order_id'] = $order_id;
                    $rec_id = M('order_goods')->add($val);
                    if(!$rec_id)
                        $this->error('添加失败');                                  
                }
                $this->success('添加商品成功',U("Admin/Order/detail",array('order_id'=>$order_insert_id)));
                exit();
            }
            else{
                $this->error('添加失败');
            }                
        }     
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);        
        return $this->fetch();
    }
    
    /**
     * 选择搜索商品
     */
    public function search_goods()
    {
    	$brandList =  M("brand")->select();
    	$categoryList =  M("goods_category")->select();
    	$this->assign('categoryList',$categoryList);
    	$this->assign('brandList',$brandList);   	
    	$where = ' is_on_sale = 1 ';//搜索条件
    	I('intro')  && $where = "$where and ".I('intro')." = 1";
    	if(I('cat_id')){
    		$this->assign('cat_id',I('cat_id'));    		
            $grandson_ids = getCatGrandson(I('cat_id')); 
            $where = " $where  and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
                
    	}
        if(I('brand_id')){
            $this->assign('brand_id',I('brand_id'));
            $where = "$where and brand_id = ".I('brand_id');
        }
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
    	}  	
    	$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(10)->select();
                
        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;            
        }
        if($goodsList){
            //计算商品数量
            foreach ($goodsList as $value){
                if($value['spec_goods']){
                    $count += count($value['spec_goods']);
                }else{
                    $count++;
                }
            }
            $this->assign('totalSize',$count);
        }
        
    	$this->assign('goodsList',$goodsList);
    	return $this->fetch();
    }
    
    public function ajaxOrderNotice(){
        $order_amount = M('order')->where("order_status=0 and (pay_status=1 or pay_code='cod')")->count();
        echo $order_amount;
    }
     //下载定制图片素材
    public function down_destine_img(){
        $filename = $_GET['file'];
        $filename = "./public/upload/destine/".$filename;
        $file  =  fopen($filename, "rb");
        Header( "Content-type:  application/octet-stream ");
        Header( "Accept-Ranges:  bytes ");
        Header( "Content-Disposition:  attachment;  filename=".$_GET['file']);
        $contents = "";
        while (!feof($file)) {
            $contents .= fread($file, 8192);
        }
        echo $contents;
        fclose($file);
        exit;
    }

 public function uploadimg() {
        $rec_id = I("post.rec_id");
        $imgurl = I("post.imgurl");
        $goodinfo = M("order_goods")->where("rec_id",$rec_id)->find();
        $otherContent =  json_decode($goodinfo['other_content'],"true");
        $otherContent['despic'] = empty($otherContent['despic'])?"/public/upload/destine/0_1489368120.png":$otherContent['despic'];
        $otherContent['message'] = empty($otherContent['message'])?"":$otherContent['message'];
        $otherContent['destine_status'] = 1;//设计师定制完成
        $otherContent['workspic'][] = $imgurl;
        $data['other_content'] = json_encode($otherContent);
        $result = M("order_goods")->where("rec_id",$rec_id)->save($data);
        if($result){
            $back['status'] = 1;
            $back['msg'] = "操作成功";
            $back['data'] = $result;
        }else{
            $back['status'] = 0;
            $back['msg'] = "操作失败";
            $back['data'] = "记录修改失败";
        }
        echo  json_encode($back);
        exit();
    }
    
    public function indiana_order_list(){
    	if(IS_POST){

	    	$timegap = I('timegap');
	        if($timegap){
	        	$gap = explode('-', $timegap);
	        	$begin = strtotime($gap[0]);
	        	$end = strtotime($gap[1]);
	        }else{
	            //@new 新后台UI参数
	            $begin = strtotime(I('add_time_begin'));
	            $end = strtotime(I('add_time_end'));
	        }
	        
	        // 搜索条件
	        $condition = array();
	        $keyType = I("keytype");
	        $keywords = I('keywords','','trim');
	        
	        $consignee =  ($keyType && $keyType == 'consignee') ? $keywords : I('consignee','','trim');
	        $consignee ? $condition['consignee'] = trim($consignee) : false;
	        
	        
	        if($begin && $end){
	        	$condition['add_time'] = array('between',"$begin,$end");
	        }
	        
	        $order_sn = ($keyType && $keyType == 'order_sn') ? $keywords : I('order_sn') ;
	        $order_sn ? $condition['order_sn'] = trim($order_sn) : false;
	        
	        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
	        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
// 	        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;

	        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
	        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
// 	        $sort_order = I('order_by','DESC').' '.I('sort');
	        $sort_order = 'id DESC';
	        $count = M('user_indiana')->where($condition)->count();
	        $Page  = new AjaxPage($count,20);
	        //  搜索条件下 分页赋值
	        foreach($condition as $key=>$val) {
	            if($key == 'add_time'){
	                $between_time = explode(',',$val[1]);
	                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
	                $Page->parameter['timegap'] = $parameter_add_time;
	            }else{
	                $Page->parameter[$key]   =  urlencode($val);
	            }
	        }
	        $show = $Page->show();
	    }
	    else{
	    	$condition = array();
	    	$sort_order = 'id DESC';
	    	$count = M('user_indiana')->count();
	        $Page  = new AjaxPage($count,20);
	        $show = $Page->show();
	    }    
        //获取订单列表
        $orderList = M('user_indiana')->where($condition)->limit("$Page->firstRow,$Page->listRows")->order($sort_order)->select();
        foreach($orderList as $key=>$val){
        	$user = M("users")->where('user_id',$val['uid'])->find();
        	$orderList[$key]['user'] = $user; 
        	//$address = M("user_address")->where("address_id",$val['address_id'])->find();
        	//$orderList[$key]['address'] = $address;
        }
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }
    
    
    /*
     * 一元夺宝详细页面
     */
    public function indiana_order_info(){
    	
    	$id = I("id/d");
        $order = M('user_indiana')->where('id',$id)->find();
    	$user = M("users")->where('user_id',$order['uid'])->find();
    	$order['user'] = $user; 
    	$address = M("user_address")->where("address_id",$order['address_id'])->find();
    	if(!$address){//如果地址为空则取默认地址
    		$address = M('user_address')->where(array('user_id'=>$order['uid'],'is_default'=>1))->find(); 
    		$orderLogic = new OrderLogic();   
    		$add2 = $orderLogic->getAddressName($address['province'],$address['city'],$address['district']); 
    	    $address['address'] = $add2.$address['address'];
    	}
    	$order['address'] = $address;
    	$indiana = M('indiana_sale')->where('id',$order['indiana_id'])->find();
    	
    	$order['indiana'] = $indiana;
    	if($order['shipping_info']){
    		$order['shipping_info'] = json_decode($order['shipping_info'],true);
    	    $order['shipping_info']['shipping_name'] = M('plugin')->where('code',$order['shipping_info']['shipping_code'])->getField('name');
    	}else{
    		$order['shipping_info']=array(
	    		       'shipping_code' => '',
	    		       'invoice_no' => '' 
    		);
    	}
       
        $order['indiana_number'] = json_decode($order['indiana_number'],true);
    	
    	$action_log = json_decode($order['order_action'],true);
    	foreach($action_log as $key=>$val){
        	$action_user = M('users')->where('user_id',$val['action_user'])->find();
        	$action_log[$key]['action_user_name'] = $action_user['nickname'];
        }
        $order['order_action'] = $action_log;
        
        if($order['order_status'] == 0 && $order['pay_status'] == 0){
        	$button['pay'] = '设为已付款'; 
        }
        if($order['order_status'] == 0 && $order['pay_status'] == 1){
            $button['pay_cancel'] = '退款'; 
            if($order['is_praise'] == 1){
                $button['delivery'] = '去发货';	
            }
            
        }	
        if($order['order_status'] == 1 && $order['pay_status'] == 1){
            $button['delivery_cancel'] = '取消发货'; 
        }
        if($order['order_status'] == 5 && $order['pay_status'] == 1){
            $button['remove'] = '移除'; 
        }
        $button['invalid'] = '无效';

        $this->assign('button',$button);
        $this->assign('order',$order);
        return $this->fetch();
    }
    
    
    /*
     * 一元夺宝订单操作日志
     */
    public function indiana_order_action(){
    	
    	$id = I('id/d');
    	$type = I('type');
    	$action_note = I('note');
    	if($id && $type){
	    	$res = indiana_order_action($type,$id,$action_note);
	    	if($res !== false && $a !== false){
	            if($action == 'remove') {
	                exit(json_encode(array('status' => 1, 'msg' => '操作成功', 'data' => array('url' => U('admin/order/index')))));
	            }
	    	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
	    	}else{
	            if($action == 'remove') {
	                exit(json_encode(array('status' => 0, 'msg' => '操作失败', 'data' => array('url' => U('admin/order/index')))));
	            }
	    	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
	    	}
    	}
    	else{
    		$this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
    	}

    }
    
    
    /**
     *  一元夺宝发货页面
     */
    public function indiana_delivery_info(){
    	
    	if(IS_POST){
    		
    		$id = I('post.id');
    		$action_note = I('post.note');
    		$invoice_no = I('post.invoice_no');
    		$shipping_code = I('post.shipping_code');
    		
    		$data = I("post.");

    		if($invoice_no && $shipping_code){
    			$shipping_info = array('invoice_no'=>$invoice_no,'shipping_code'=>$shipping_code);
    			$r = M('user_indiana')->where('id',$id)->save(array('shipping_info'=>json_encode($shipping_info)));
    		}
    		else{
    			$this->success('配送方式或者物流单号不能为空',U('Admin/Order/indiana_delivery_info',array('id'=>$id)));
    		}
    		$action = 'delivery';
    		$msg = indiana_order_action($action,$id,$action_note);
    	    if($r && $msg){
				$this->success('操作成功',U('Admin/Order/indiana_order_info',array('id'=>$id)));
			}else{
				$this->success('操作失败',U('Admin/Order/indiana_delivery_info',array('id'=>$id)));
			}
    	}else{
    		$id = I('get.id');
	    	$model = M('user_indiana');
	        $order = $model->where('id',$id)->find();
	    	$user = M("users")->where('user_id',$order['uid'])->find();
	    	$order['user'] = $user; 
	    	$address = M("user_address")->where("address_id",$order['address_id'])->find();
	    	$order['address'] = $address;
	    	$indiana = M('indiana_sale')->where('id',$order['indiana_id'])->find();
	    	$order['indiana'] = $indiana;
	    	$order['shipping_info'] = json_decode($order['shipping_info'],true);	
	    	
	    	//$shipping = M('shipping')->select();
            $shipping = M('plugin')->where(array('type'=>'shipping','status'=>1))->select();
            $this->assign('shipping',$shipping);
	        $this->assign('order',$order);
	        return $this->fetch();
    	}
    }
    
    
    //微信退款
    function WX_refund(){
        if(IS_AJAX){
            $order_sn  = I("post.order_sn");
            $user_id = I("post.user_id");
            $back_money = I("post.back_money");
            //取得支付信息
            $pay_info = M("pay_log")->where("order_sn=$order_sn")->find();
            if($back_money*100 > $pay_info['total_fee']){
                $back['status'] = 0;
                $back['msg'] = "退款金额大于支付金额，退款失败";
                $back['data'] = "退款金额大于支付金额，退款失败";
                echo json_encode($back);
                exit();
            }
            if($pay_info){
                //查询是否已退款
                $refund_info = M("refund_log")->where(array("pay_id"=>$pay_info['pay_id'],"user_id"=>$user_id))->find();
                if(empty($refund_info)){
                    $refund_log=array(
                        'pay_id' => $pay_info['pay_id'],
                        'user_id'=> $user_id,
                        'out_trade_no'=>$pay_info['out_trade_no'],
                        'out_refund_no'=>"WXTK".getOrdersn(),
                        'refund_fee'=>$back_money*100,
                        'op_user_id'=>"1400627102",
                        'addtime'=>time(),
                        'status'=>0,//审核中
                        'return_type'=>1,//退款至账户
                    );
                    $refund_info['refund_id'] = M("refund_log")->add($refund_log);
                }else{
                    if($refund_info['status'] == 1){//已退款
                        $back['status'] = 0;
                        $back['msg'] = "该订单已有退款信息，请勿重复退款";
                        $back['data'] = "该订单已有退款信息，请勿重复退款";
                        echo json_encode($back);
                        exit();
                    }
                }
                //微信退款
                $result = order_WX_refund($refund_info['refund_id']);
                if($result){
                    $back['status'] = 1;
                    $back['msg'] = "退款成功";
                    $back['data'] = "退款成功";
                }else{
                    $back['status'] = 0;
                    $refund = M("refund_log")->where("refund_id",$refund_info['refund_id'])->find();
                    $back['msg'] = "退款失败,错误原因:".$refund['err_msg'];
                    $back['data'] = "退款失败,参数错误";
                }
            }else{
                $back['status'] = 0;
                $back['msg'] = "该订单无支付信息，退款失败";
                $back['data'] = "该订单无支付信息，退款失败";
            }
        }else{
            $back['status'] = 0;
            $back['msg'] = "无效访问";
            $back['data'] = "无效访问";
        }
        echo json_encode($back);
        exit();
    }
    
    //支付宝退款
    function alipay_refund() {
        alipay_refund();
    }
}
